<template>
  <div>
    <div id="app">
      <div>
        <span>姓名:</span>
        <input type="text" v-model="arr[0].name" />
      </div>
      <div>
        <span>年龄:</span>
        <input type="number" v-model="arr[0].age" />
      </div>
      <div>
        <span>性别:</span>
        <select v-model="arr[0].gender">
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>
      <div>
        <button @click="add">添加/修改</button>
      </div>
      <div>
        <table border="1" cellpadding="10" cellspacing="0">
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>操作</th>
          </tr>
          <tr v-for="(item, index) in list" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.gender }}</td>
            <td>
              <button @click="del(item.id)">删除</button>
              <button @click="bianji(item.id)">编辑</button>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { id: 1, name: "Tom", age: 20, gender: "男" },
        { id: 2, name: "Jam", age: 19, gender: "女" },
      ],
      arr: [{ id: +new Date(), name: "", age: 0, gender: "" }],
      outadd: 0,
    };
  },
  methods: {
    add() {
      if (this.name1 === "" || this.age1 === 0 || this.gender1 === "") {
        alert("不能为空");
        return;
      }

      if (this.outadd === 0) {
        this.list.push({ ...this.arr[0] });
      } else {
        this.list.splice(
          this.list.findIndex((item) => item.id === this.outadd),
          1,
          { ...this.arr[0] }
        );
      }

      this.arr[0].name = "";
      this.arr[0].age = 0;
      this.arr[0].gender = "";

      this.outadd = 0;
    },
    bianji(id) {
      //  this.arr.splice(0,1,this.list.filter(item => item.id === id )[0])
      // let aaa = Object.assign({},this.list.filter(item => item.id === id )[0])
      let aaa = { ...this.list.filter((item) => item.id === id)[0] };
      this.arr = [aaa];
      this.outadd = id;
    },
    del(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
  },
};
</script>

<style>
.wrap {
  width: 100%;
  display: flex;
  margin: 0.2rem 0 0 0;
  position: relative;
}

/*左侧的导航样式*/
.nav_left {
  width: 21.1875rem;
  overflow: scroll;
}

.nav_left::-webkit-scrollbar {
  display: none;
}

.nav_content {
  white-space: nowrap;
  padding: 0 0.7rem;
}

.nav_content span {
  display: inline-block;
  padding: 0.4rem 0.6rem;
  font-size: 0.875rem;
}

.nav_content .active {
  border-bottom: 2px solid #7f4395;
  color: #7f4395;
}

.nav_left,
.down {
  float: left;
}
</style>